﻿var Form = antd.Form;
var Input = antd.Input;
var Row = antd.Row;
var Col = antd.Col;
var Button = antd.Button;
var message=antd.message;
var Icon = antd.Icon;
var Modal = antd.Modal;
var Select = antd.Select;
var Checkbox = antd.Checkbox;
var Radio = antd.Radio;
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const createForm = Form.create;
var Table = antd.Table;

var Collapse =antd.Collapse;
const Panel = Collapse.Panel;

class BasicUserInfo extends React.Component {
    getValidateStatus(field) {
        const { isFieldValidating, getFieldError, getFieldValue } = this.props.form;

        if (isFieldValidating(field)) {
            return 'validating';
        } else if (!!getFieldError(field)) {
            return 'error';
        } else if (getFieldValue(field)) {
            return 'success';
        }
    }

    handleReset(e) {
        e.preventDefault();
        this.props.form.resetFields(); 
       this.props.modalhide();     
    }
    handleSubmit(e) {
        e.preventDefault();
        var that=this;
        this.props.form.validateFields((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            console.log(values);
            $.ajax({
                url: '/User/InsertOrUpdate',
                contentType: "application/json; charset=utf-8",
                type: "POST",
                dataType: "json",
                data:JSON.stringify(values),
                cache:false,
                success:function(result){
                    if(!result.error)
                    {
                        message.success('添加成功!');
                        that.props.form.resetFields();
                        that.props.tablereload();
                        that.props.modalhide();
                    }
                    else
                    {
                        message.error(result.message);
                    }
                } ,
                error: function(x, e) {
                    message.error(x.responseText);
                    console.log(x.responseText);
                },
                complete: function(x) {
                    
                  
                }
            });
        });
    }
    userExists(rule, value, callback) {
        if (!value) {
            callback();
        } else {
            setTimeout(() => {
                if (value === 'JasonWood') {
                    callback([new Error('抱歉，该用户名已被占用。')]);
                } else {
                    callback();
                }
            }, 800);
        }
    }
    render() {
        const { getFieldProps, getFieldError, isFieldValidating } = this.props.form;
        var modal=this.props.modal;
		var id=0;
		var name="";
		var phoneno="";
		var enablevalue="true";
		var phonesn="";
			console.log(enablevalue);
	    if (typeof(modal)!='undefined' && modal.ID!=undefined )
       {
			id=modal.ID;
			name=modal.UserName;
			phoneno=modal.PhoneNo;
			phonesn=modal.PhoneSn;
			enablevalue=modal.Enable.toString();
			console.log(enablevalue);
	    }
	  
        const nameProps = getFieldProps('username', {
            rules: [
              { required: true, min: 2, message: '用户名至少为 2 个字符' },
              { validator: this.userExists },
            ],
			initialValue:name
			
        });
        const idProps=getFieldProps('id', { initialValue :id});

        const phonesnProps= getFieldProps('PhoneSn', {
            initialValue:phonesn
        });
	   const phonenoProps = getFieldProps('PhoneNo', {
      rules: [
	     { required: true, min: 4, message: '用户帐号至少为 4 个字符' },
      ],
	  initialValue:phoneno
    });
	const enableProps=getFieldProps('enable', { initialValue :enablevalue });
        const formItemLayout = {
            labelCol: { span: 7 },
            wrapperCol: { span: 12 },
        };
        return (
          <Form horizontal form={this.props.form}>
		  <div >
		     <FormItem 
        {...formItemLayout}
          label="ID："
       >
          <Input  disabled={true}  {...idProps}  />
        </FormItem>
		</div>
        <FormItem
        {...formItemLayout}
          label="用户名："
          hasFeedback
          help={isFieldValidating('username') ? '校验中...' : (getFieldError('username') || []).join(', ')}>
          <Input {...nameProps} placeholder="用户名称" />
        </FormItem>

          <FormItem
        {...formItemLayout}
          label="电话号码："
          hasFeedback
         >
         <Input {...phonenoProps}  placeholder="电话号码" id="PhoneNo" name="PhoneNo" />
        </FormItem>

                 <FormItem {...formItemLayout}
                           label="机器码："
                           hasFeedback>
         <Input {...phonesnProps}  placeholder="机器码" id="PhoneSN" name="PhoneSN" />
                 </FormItem>

           <FormItem {...formItemLayout}
                     label="是否启用：">
          <RadioGroup {...enableProps}>
            <Radio value="true">是</Radio>
            <Radio value="false">否</Radio>
          </RadioGroup>
           </FormItem>
        <FormItem wrapperCol={{ span: 12, offset: 7 }}>
          <Button type="primary" onClick={this.handleSubmit.bind(this)}>确定</Button>
          &nbsp;&nbsp;&nbsp;
<Button type="ghost" onClick={this.handleReset.bind(this)}>取消</Button>
</FormItem>
</Form>
    );
}
}

BasicUserInfo = createForm()(BasicUserInfo);
const UserMnt = React.createClass({
    getInitialState() {
        return {
            data: [],
            pagination: {},
            loading: false,
        };
    },
    handleTableChange(pagination, filters, sorter) {
        const pager = this.state.pagination;
        pager.current = pagination.current;
        this.setState({
            pagination: pager
        });
        const params = {
            pageSize: pagination.pageSize,
            currentPage: pagination.current,
            sortField: sorter.field?sorter.field:"",
            sortOrder: sorter.order?sorter.order:"",

        };
        for (let key in filters) {
            if (filters.hasOwnProperty(key)) {
                params[key] = filters[key];
            }
        }
        this.fetch(params);
    },
    search() {
   
        this.setState({ loading: true });
        const pager = this.state.pagination;
        pager.current = 1;
        this.setState({
            pagination: pager
        });

        this.fetch();
    },
    fetch(params = {}) {
        if(!params.pageSize)
        {
            params = {
                pageSize:10,
                currentPage: 1,
                sortField: "",
                sortOrder:"",
      

            };
        }
        this.setState({ loading: true });
        const pagination = this.state.pagination;
        var that=this;
        $.ajax({
            url: '/User/GetPage',
            contentType: "application/json; charset=utf-8",
            type: "POST",
            dataType: "json",
            data:JSON.stringify(params),
            cache:false,
            success:function(result){
         
                pagination.total = result.totalCount;
                that.setState({
                    loading: false,
                    data: result.data,
                    pagination,
                });
            } ,
            error: function(x, e) {
                alert(x.responseText);
            },
            complete: function(x) {

            }
        });
    },
  componentDidMount() {
      this.fetch();
  },

 showModal(value) {
	 var modalid=value.currentTarget.id;	
	 console.log(modalid);
	 var that=this;
	 var modal={};
    if (!modalid && typeof(modalid)!="undefined" && modalid=="")
    {
	     this.setState({
         visible: true,
		 modal:{}
     });
    }
	else{ 
	 	var params={ID:modalid};
	    $.ajax({
	        url: '/User/Get',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        dataType: "json",
        data:JSON.stringify(params),
        cache:false,
        success:function(result){
			 that.setState({
         visible: true,
		 modal:result
     });
           // message.success('获取成功');
        } ,
        error: function(x, e) {
            message.error(x.responseText);

        },
        complete: function(x) {
           
        }
    });
	 }
 },
 handleOk() {
   

 },
    handleCancel() {
        this.setState({ visible: false });
    },
 deleteuserinfo(value)
{
    var that=this;
    console.log(value);
    const params = {
        id:value.currentTarget.id
    };
    $.ajax({
         url: '/User/Delete',
        contentType: "application/json; charset=utf-8",
        type: "POST",
        dataType: "json",
        data:JSON.stringify(params),
        cache:false,
        success:function(rt){
            message.success('删除成功！');
        } ,
        error: function(x, e) {
            message.error(x.responseText);

        },
        complete: function(x) {
            that.search();
        }
    });

},
  getValidateStatus(field) {
      const { isFieldValidating, getFieldError, getFieldValue } = this.props.form;
      if (isFieldValidating(field)) {
          return 'validating';
      } else if (!!getFieldError(field)) {
          return 'error';
      } else if (getFieldValue(field)) {
          return 'success';
      }
  },
  render() {
     
      var that=this; 
      const   columns = [
      {
          title: '操作',
          key: 'operation',
          render(text, record) {
              return (
          <span>
		   <a id={record.ID} onClick={  that.deleteuserinfo  }>删除</a> &nbsp;
		      <a id={record.ID} onClick={  that.showModal  }>编辑</a> &nbsp;
          </span>
        );
          }
      },
{
    title: '用户名',
    dataIndex: 'UserName',
}, {
    title: '电话号码',
    dataIndex: 'PhoneNo',
}
, {
    title: '机器码',
    dataIndex: 'PhoneSn',
}
, {
    title: '创建时间',
    dataIndex: 'CreateTime',
}, {
    title: '更新时间',
    dataIndex: 'UpdateTime'
}
      ];
  
      return (
          <div>
           <div id="search"></div>
          
              <Button type="primary" onClick={this.showModal}>
                 新增
             </Button>       

            <Modal ref="modal"
                   visible={this.state.visible} modalid={this.state.modalid}
                   title="新增" onOk={this.handleOk} onCancel={this.handleCancel}
                   footer={[]}>
		     <BasicUserInfo modal={this.state.modal} modalhide={this.handleCancel} tablereload={this.search} />
            </Modal>
           <Table columns={columns}
                  size="small" rowKey={record => record.ID}
                  dataSource={this.state.data}
                  pagination={this.state.pagination}
                  loading={this.state.loading}
                  onChange={this.handleTableChange} bordered />
         </div>
);
  }
});